package org.kl.bpm.service.conf;

import java.util.List;
import java.util.Map;

import org.kl.bf.utils.CRUDUtils;
import org.kl.bpm.entity.conf.BpmConfNode;
import org.kl.bpm.repository.conf.BpmConfNodeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

/**
 * 
 * @Author hqm
 * @CreateTime 2014年5月25日 下午8:40:29
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class BpmConfNodeService {

	private BpmConfNodeDao bpmConfNodeDao;

	public BpmConfNode getBpmConfNode(String id) {
		return bpmConfNodeDao.findOne(id);
	}

	public BpmConfNode findByCodeAndBpmConfBaseId(String code, String confBaseId) {
		return bpmConfNodeDao.findByCodeAndBpmConfBaseId(code, confBaseId);
	}

	public void save(BpmConfNode entity) {
		bpmConfNodeDao.save(entity);
	}

	public void deleteBpmConfNode(String id) {
		bpmConfNodeDao.delete(id);
	}

	public List<BpmConfNode> getAllBpmConfNode() {
		return bpmConfNodeDao.findAll();
	}

	public List<BpmConfNode> findByBpmConfBaseIdOrderByPriorityAsc(String bpmConfBaseId) {
		return bpmConfNodeDao.findByBpmConfBaseIdOrderByPriorityAsc(bpmConfBaseId);
	}

	public List<BpmConfNode> searchAll(Map<String, Object> searchParams, String sortType, String orderType) {
		return bpmConfNodeDao.searchAll(searchParams, sortType, orderType,BpmConfNode.class);
	}

	public Page<BpmConfNode> getUserBpmConfNode(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<BpmConfNode> spec = buildSpecification(searchParams);

		return bpmConfNodeDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<BpmConfNode> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<BpmConfNode> spec = DynamicSpecifications.bySearchFilter(filters.values(), BpmConfNode.class);
		return spec;
	}

	@Autowired
	public void setBpmConfNodeDao(BpmConfNodeDao bpmConfNodeDao) {
		this.bpmConfNodeDao = bpmConfNodeDao;
	}

}
